<?php
/*
Plugin Name: contentFilter
Plugin URI: http://www.yhustc.com/
Description: 内容过滤,将日志详细内容中TAG对应的词替换为链接
Author: yhustc
Version: 1.0
Author URI: http://www.yhustc.com/
*/

function replaceTags($content)
{
	$tags = S("tags");
	if(!$tags)
	{
		$Dao = D("Tags");
		$tags = $Dao->findAll();

		//为了防止重复替换,比如<a>tags</a>　str_replace('tag')
		//先把所有的tag按字长排个序
		//使用preg_replace也不好匹配,因为<a>tags</a>要搜索tag是否已经有一个类似的链接了,不好定义规则
		foreach($tags as $id=>$tag)
		{
			if(function_exists("mb_strlen"))
				$tags[$id]["len"] = mb_strlen($tag["name"]);
			else
				$tags[$id]["len"] = strlen($tag["name"]);
		}
		
		$tags = Array_sort_by_field($tags, "len"); //按len的升序排列二维数组
		S("tags",$tags);
	}
	
	//先把所有的a img全取出来,免得HTML里面的关键字被替换掉了
	preg_match_all('/<[^>]+>/', $content, $htmlTag, PREG_PATTERN_ORDER);
	for ($i = 0; $i < count($htmlTag[0]); $i++) {
		$content = str_replace($htmlTag[0][$i],'<!-- html'.$i.' -->',$content);
	}

	$search = array();
	$replace = array();
	foreach($tags as $tag)
	{
		$search[] = $tag["name"];
		$replace[] = "<a href='".url(urlencode($tag["name"]),'Tag')."' title='查看该标签下所有相关日志'>".Input::forShow($tag["name"])."</a>";
	}
	$content = str_replace($search,$replace,$content);

	for ($i = 0; $i < count($htmlTag[0]); $i++) {
		$content = str_replace('<!-- html'.$i.' -->',$htmlTag[0][$i],$content);
	}
	
	return $content;
}

add_filter("content_filter","replaceTags");
?>